import { Injectable } from '@nestjs/common'
import { InjectRepository } from '@nestjs/typeorm'
import { Repository } from 'typeorm'
import { CreateProductDto } from './dto/create-product.dto'
import { ImagesEntity } from './entities/images.entity'
// import { UpdateProductDto } from './dto/update-product.dto'
import { ProductEntity } from './entities/product.entity'

@Injectable()
export class ProductsService {
  constructor(
    @InjectRepository(ImagesEntity)
    private readonly imagesRepository: Repository<ImagesEntity>,
    @InjectRepository(ProductEntity)
    private readonly repository: Repository<ProductEntity>
  ) {
  }

  create(createProductDto: CreateProductDto) {
    return this.repository.save(createProductDto)
  }

  findAll() {
    return this.repository.find()
  }

  /**
   * 获取商品详情
   * @param id 产品 Id
   * @returns
   */
  findOne(id: number) {
    return this.repository.find({
      where: { id }
    })
  }

  /**
   * 根据分类id查询产品列表
   * @param id
   */
  async findOneByCategoryId(id: number, sort: any = { sort_order: 'DESC' }, page = 1, limit = 10) {
    console.log('id', id)
    console.log('id', sort)
    const list = await this.repository.createQueryBuilder('product')
      .where('product.category_id = :category_id', { category_id: id })
      .skip((page - 1) * limit)
      .take(limit)
      .getManyAndCount()

    return list
  }

  /**
   * 获取商品图片
   */
  findImages(id: number) {
    return this.imagesRepository.find({
      where: { product_id: id }
    })
  }

  remove(id: number) {
    return `This action removes a #${id} product`
  }
}
